package com.mchat.util;

import com.google.protobuf.Timestamp;
import io.jsonwebtoken.Claims;
import org.springframework.web.server.ServerWebExchange;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class Utils {
    public static Long getUid(ServerWebExchange exchange) {
        return Long.valueOf(((Claims) Objects.requireNonNull(exchange.getAttribute("claims"))).getSubject());
    }

    //将一个list拆分为多个子list，每个list大小为size
    public static <T> List<List<T>> splitList(List<T> list, int size) {
        List<List<T>> result = new ArrayList<>();
        int total = list.size();
        for (int i = 0; i < total; i += size) {
            int end = Math.min(total, i + size);
            //使用原来的空间
            result.add(list.subList(i, end));
        }
        return result;
    }
    public static LocalDateTime fromProtoTimestamp(Timestamp timestamp) {
        return LocalDateTime.ofInstant(
                Instant.ofEpochSecond(timestamp.getSeconds(), timestamp.getNanos()),
                ZoneId.systemDefault()
        );
    }
    public static Timestamp toProtoTimestamp(LocalDateTime localDateTime) {
        return Timestamp.newBuilder()
                .setSeconds(localDateTime.atZone(ZoneId.systemDefault()).toEpochSecond())
                .setNanos(localDateTime.getNano())
                .build();
    }
}
